package gov.pbc.gx.nn.pz.dao;

import gov.pbc.gx.nn.pz.entity.Account;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;

@Repository
public class AccountDao extends AbstractHibernateDao {

	@Transactional
	@DataResolver
	public void save(List<Account> list) {

		for (Account account : list) {

			EntityState s = EntityUtils.getState(account);
			if (s == EntityState.NEW) {
				this.save(account);
			} else if (s == EntityState.MODIFIED) {
				this.update(account);
			}
		}

	}

	@Expose
	@Transactional
	public void delete(String id) {
		this.delete(id, Account.class);
	}

	@Expose
	public void checkUnique(String id, String account) {
		String hql = null;
		Map<String, Object> map = new HashMap<String, Object>();
		if (id == null) {

			hql = "select count(*) from Account where account =:account and invalid=false";
		} else {
			hql = "select count(*) from Account where account =:account and id !=:id and invalid=false";
			map.put("id", id);
		}
		map.put("account", account);

		List<Object> list = this.query(hql, map);

		Number n = (Number) list.get(0);
		if (n.intValue() > 0) {
			throw new RuntimeException("账号已存在，请重新输入");
		}
	}
}
